package com.cheng.lesson02;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class TCPServerDemon01 {
    public static void main(String[] args) {
        //提升作用域
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            //1.服务端的地址 localhost:7777
            serverSocket = new ServerSocket(7777);
            //2.等待来自客户端的连接
            socket = serverSocket.accept();
            //3.读取客户端的消息
            inputStream = socket.getInputStream();

            //4.管道流 ByteArrayOutputStream： 字节数组输出流,可以捕获内存缓冲区的数据，转换成字节数组。
            byteArrayOutputStream = new ByteArrayOutputStream();//创建字节数组输出流对象
            byte[] buffer = new byte[1024];//定义字节数组缓冲区接收消息
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);//从指定数组的下标off开始写入len个字节到该输出流中
            }
            System.out.println(byteArrayOutputStream.toString());//避免乱码

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源，先开后关
            if (byteArrayOutputStream != null) {

                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}